import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import _ from "lodash";
import {
  Button,
  Form,
  Select,
  Input,
  TreeSelect,
  Radio,
  Switch,
  message,
  Tooltip,
  Icon,
} from "antd";
import { useDynamicList } from "@umijs/hooks";
import { renderTreeNodes } from "@pkgs/Layout/utils";
import useFormatMessage from "@pkgs/hooks/useFormatMessage";
import { nameRule } from "../config";
import Editor from "./Editor";
import { RadioChangeEvent } from "antd/lib/radio";
import request from "@pkgs/request";
import api from "@common/api";

const FormItem = Form.Item;
const { Option } = Select;

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const defaultFormData = {
  collect_type: "check",
  timeout: 3,
  step: 10,
  ctype: "custom",
  status: false,
  comment: "#!/bin/bash\n# e.g.\n",
};

const getInitialValues = (initialValues: any) => {
  return _.assignIn({}, defaultFormData, _.cloneDeep(initialValues));
};

const CollectForm = (props: any) => {
  const intlFmtMsg = useFormatMessage();
  const initialValues = getInitialValues(props.initialValues);
  const { getFieldProps, getFieldDecorator, setFieldsValue } = props.form;
  const [submitLoading, setSubmitLoading] = useState(false);
  const [templates, setTemplates] = useState([]);
  const [temp, setTemp] = useState("custom");
  const [selected, setSelected] = useState(initialValues.comment);

  if (initialValues.env) {
    try {
      const env = JSON.parse(initialValues.env);
      initialValues.env = _.map(env, (value: any, name: any) => {
        return {
          name,
          value,
        };
      });
    } catch (e) {
      console.log(e);
    }
  }

  const { resetList } = useDynamicList(initialValues.env);

  useEffect(() => {
    resetList(initialValues.env);
  }, [JSON.stringify(initialValues.env)]);

  useEffect(() => {
    if (initialValues.ctype === "init") {
      request(`${api.getTmp}/list`)
        .then((res) => {
          setTemplates(res);
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }, [initialValues.ctype]);

  getFieldDecorator("collect_type", {
    initialValue: initialValues.collect_type,
  });

  getFieldDecorator("comment", {
    initialValue: initialValues.comment,
  });

  getFieldDecorator("status", {
    initialValue: initialValues.status,
  });

  const ctypeOnChange = (e: RadioChangeEvent) => {
    const temName = e.target.value;
    if (temName === "init") {
      request(`${api.getTmp}/list`).then((res) => {
        if (res.length) {
          setTemplates(res);
        } else {
          setTemplates([]);
          message.warning("无巡检模板！");
        }
      });
      setTemp("init");
    } else {
      setTemplates([]);
      setTemp("custom");
    }
  };

  const handleSubmit = (e: any) => {
    e.preventDefault();
    props.form.validateFields((errors: any, values: any) => {
      if (errors) {
        console.error(errors);
        return;
      }
      setSubmitLoading(true);
      if (values.env) {
        const { env } = values;
        const newEnv: any = {};
        _.forEach(env, (item: { name: string | number; value: any }) => {
          newEnv[item.name] = item.value;
        });
        values.env = JSON.stringify(newEnv);
      }
      const cron = values["cron"].trim();
      values = { ...values, cron };
      props.onSubmit(values).catch(() => {
        setSubmitLoading(false);
      });
    });
  };

  const onChange = (value: string) => {
    setSelected(value);
    setFieldsValue({ comment: value });
  };

  useEffect(() => {
    setSelected(initialValues.comment);
  }, [initialValues.comment]);

  return (
    <Form layout="horizontal" onSubmit={handleSubmit}>
      <FormItem
        {...formItemLayout}
        label={intlFmtMsg({ id: "collect.common.node" })}
      >
        {getFieldDecorator("nid", {
          initialValue: initialValues.nid,
          rules: [{ required: true, message: "请选择节点！" }],
        })(
          <TreeSelect
            style={{ width: 500 }}
            showSearch
            allowClear
            treeDefaultExpandAll
            treeNodeFilterProp="path"
            treeNodeLabelProp="path"
            dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
          >
            {renderTreeNodes(props.treeData, "treeSelect")}
          </TreeSelect>
        )}
      </FormItem>

      <FormItem
        {...formItemLayout}
        label={intlFmtMsg({ id: "collect.common.name" })}
      >
        <Input
          {...getFieldProps("name", {
            initialValue: initialValues.name,
            rules: [{ required: true, message: "必填项！" }, nameRule],
          })}
          size="default"
          style={{ width: 500 }}
          placeholder={intlFmtMsg({ id: "collect.plugin.name.placeholder" })}
        />
      </FormItem>

      <FormItem
        {...formItemLayout}
        label={intlFmtMsg({ id: "collect.check.ctype" })}
      >
        {getFieldDecorator("ctype", {
          initialValue: initialValues.ctype,
        })(
          <Radio.Group onChange={ctypeOnChange}>
            <Radio value={"custom"}>
              <Tooltip
                placement="topLeft"
                title={intlFmtMsg({
                  id: "collect.check.comment.custom.prompt",
                })}
              >
                个性化检查&nbsp;
                <Icon type="exclamation-circle" style={{ fontSize: 12 }} />
              </Tooltip>
            </Radio>
            <Radio value={"init"}>
              <Tooltip
                placement="topLeft"
                title={intlFmtMsg({
                  id: "collect.check.comment.init.prompt",
                })}
              >
                通用检查&nbsp;
                <Icon type="exclamation-circle" style={{ fontSize: 12 }} />
              </Tooltip>
            </Radio>
          </Radio.Group>
        )}
      </FormItem>

      {temp !== "custom" && (
        <FormItem
          {...formItemLayout}
          label={intlFmtMsg({ id: "collect.check.comment_select" })}
        >
          <Select
            size="default"
            style={{ width: 150 }}
            onChange={onChange}
            placeholder="请选择巡检模板"
          >
            {_.map(templates, (item: any) => (
              <Option key={item.id} value={item.comment}>
                {item.name}
              </Option>
            ))}
          </Select>
        </FormItem>
      )}

      <FormItem
        {...formItemLayout}
        label={intlFmtMsg({ id: "collect.check.comment" })}
      >
        {getFieldDecorator("comment", {
          initialValue: selected,

          rules: [{ required: true, message: "必填项！" }],
        })(<Editor />)}
      </FormItem>

      <FormItem
        {...formItemLayout}
        label={
          <Tooltip
            placement="topLeft"
            title={<span>{intlFmtMsg({ id: "collect.check.cron.prompt" })}</span>}
          >
            {intlFmtMsg({ id: "collect.check.cron" })}&nbsp;
            <Icon
              type="exclamation-circle"
              style={{
                fontSize: "11px",
                position: "absolute",
                top: "-4px",
              }}
            />&nbsp;&nbsp;&nbsp;
          </Tooltip>
        }
      >
        <Input
          {...getFieldProps("cron", {
            initialValue: initialValues.cron,
            rules: [
              {
                required: true,
                pattern:
                  /^(0|[1-9]|[1-5][0-9])(\s(2[0-3]|1[0-9]|[0-9]|\*))(\s(3[0-1]|[12][0-9]|[0-9]|\*))(\s(1[0-2]|[0-9]|\*))(\s(0|[1-7]|\*))$/,
                message:
                  "字符串按空格切分后长度必须等于5,第一个元素必须是0-59的数字,其余的可以是*也可以是数字,符合cron分时日月周规则",
              },
            ],
          })}
          style={{ width: 500 }}
          placeholder={intlFmtMsg({ id: "collect.check.comment.placeholder" })}
        />
      </FormItem>

      <FormItem
        {...formItemLayout}
        label={intlFmtMsg({ id: "collect.check.status" })}
      >
        {getFieldDecorator("status", {
          valuePropName: "checked",
        })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
      </FormItem>

      <FormItem wrapperCol={{ offset: 6 }} style={{ marginTop: 24 }}>
        <Button type="primary" htmlType="submit" loading={submitLoading}>
          {intlFmtMsg({ id: "form.submit" })}
        </Button>
        <Button style={{ marginLeft: 8 }}>
          <Link
            to={{ pathname: "/collect/check", search: window.location.search }}
          >
            {intlFmtMsg({ id: "form.goback" })}
          </Link>
        </Button>
      </FormItem>
    </Form>
  );
};

export default Form.create()(CollectForm);
